package yin.com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/index.jsp")
public class Afffilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Cookie[] cookies = req.getCookies();
         if (null != cookies && cookies.length > 0){
           boolean tag = false;
             for (Cookie c:cookies) {
                 if ("name".equals(c.getName())){
                      tag=true;
                      break;
                 }
             }
             if (tag){
                 Object obj = req.getSession().getAttribute("userId");
                 if (null != obj){
                     resp.sendRedirect(req.getContextPath()+"/view/home");
                     return;
                 }
             }

         }
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
